package com.xxxx.server.config;

import com.xxxx.server.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.simp.config.ChannelRegistration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.messaging.simp.stomp.StompCommand;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.messaging.support.ChannelInterceptor;
import org.springframework.messaging.support.MessageHeaderAccessor;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.util.StringUtils;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;

import javax.annotation.Resource;

/**
 * @Author : ymd
 * @Date : 2020/10/16 0016 14:33
 * @Version 1.0
 * @Description : 网页在线聊天配置
 */
@Configuration
//开启stomp协议传输基于message broker的消息
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
    @Value("${jwt.tokenHead}")
    private String tokenHead;
    @Resource
    private JwtUtils jwtUtils;
    @Resource
    private UserDetailsService userDetailsService;

    /**
     * 添加Endpoint，网页就可以通过websocket连接服务
     * 注册stomp协议节点 endpoint
     * @param registry
     */
    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        //1.将/ws/ep路径注册为s的端点，用户连接了这个端点（即自定义的接口）
        // 通过访问http://localhost:8080/ws/ep就可以进行websocket通讯
        //2.setAllowedOrigins：允许跨域
        //3.withSockJS：支持socketJS访问
        registry.addEndpoint("/ws/ep").setAllowedOrigins("*").withSockJS();
    }

    //“clientInboundChannel” — 用于传递从WebSocket客户端接收到的消息。
    //“clientOutboundChannel” — 用于向WebSocket客户端发送服务器消息。
    //“brokerChannel” — 用于从服务器端的应用程序代码中向message broker或 stomp broker relay发送消息。

    /**
     * 配置客户端入站通道拦截器，用于传递从WebSocket客户端接收到的消息
     * 此处可以监控用户聊天时的上下线
     * @param registration
     */
    @Override
    public void configureClientInboundChannel(ChannelRegistration registration) {
        registration.interceptors(new ChannelInterceptor() {
            @Override
            public Message<?> preSend(Message<?> message, MessageChannel channel) {
                //Stomp标头访问器,用于接收消息
                StompHeaderAccessor accessor=MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
                //判断是否连接websocket ,连接则需要token令牌
                if(StompCommand.CONNECT.equals(accessor.getCommand())){
                    //与前端连接时对应
                    String token = accessor.getFirstNativeHeader("Auth-Token");
                    //令牌非空校验
                    if(!StringUtils.isEmpty(token)){
                        //截取令牌
                        String authToken = token.substring(tokenHead.length());
                        //获取用户名
                        String username = jwtUtils.getUserNameFromToken(authToken);
                        //用户名非空校验
                        if (!StringUtils.isEmpty(username)){
                            //登录
                            UserDetails userDetails = userDetailsService.loadUserByUsername(username);
                            //验证token令牌是否有效，重新设置用户对象
                            if (jwtUtils.validateToken(authToken,userDetails)){
                                UsernamePasswordAuthenticationToken authenticationToken =
                                        new UsernamePasswordAuthenticationToken(userDetails, null,
                                                userDetails.getAuthorities());
                                //上下文设置身份验证
                                SecurityContextHolder.getContext().setAuthentication(authenticationToken);
                                //设置聊天用户
                                accessor.setUser(authenticationToken);
                            }
                        }
                    }
                }
                return message;
            }
        });
    }

    /**
     * 配置代理消息
     * @param registry
     */
    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        //订阅broker名称
        registry.enableSimpleBroker("/queue");
    }
}
